
package net.vinote.smart.platform.module.i18n;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.ResourceBundle;

/**
 * 实现国际化的工具类
 * 
 * @author 郑俊伟
 * 
 */
public final class Message
{

	private List<ResourceMetadata> i18nDirList;

	private Locale locale;

	/**
	 * 添加国际化资源文件的解析目录
	 * 
	 * @param dir
	 */
	public void addI18N(String dir, ClassLoader loader)
	{
		if (i18nDirList == null)
		{
			// Base Layer,Service Layer,Customize Layer
			i18nDirList = new ArrayList<ResourceMetadata>(3);
		}
		i18nDirList.add(0, new ResourceMetadata(dir, loader));
	}

	public void setLocal(Locale locale)
	{
		if (locale == null)
		{
			locale = Locale.getDefault();
		}
		this.locale = locale;
	}

	/*
	 * public ResourceBundle getMessage() { if (locale == null) { locale =
	 * Locale.getDefault(); } return ResourceBundle.getBundle(i18nBase, locale);
	 * }
	 */
	public String getMessage(String key)
	{
		for (ResourceMetadata rl : i18nDirList)
		{
			ResourceBundle rb = null;
			if (rl.loader == null)
			{
				rb = ResourceBundle.getBundle(rl.baseName, locale);
			}
			else
			{
				rb = ResourceBundle.getBundle(rl.baseName, locale, rl.loader);
			}
			if (rb.containsKey(key))
			{
				return rb.getString(key);
			}
		}
		return null;
	}

	public Map<String, String> getMessage()
	{
		Map<String, String> map = new HashMap<String, String>();
		for (ResourceMetadata rm : i18nDirList)
		{
			ResourceBundle rb = null;
			if (rm.loader == null)
			{
				rb = ResourceBundle.getBundle(rm.baseName, locale);
			}
			else
			{
				rb = ResourceBundle.getBundle(rm.baseName, locale, rm.loader);
			}
			for (String key : rb.keySet())
			{
				map.put(key, rb.getString(key));
			}
		}
		return map;
	}

	private class ResourceMetadata
	{
		String baseName;

		ClassLoader loader;

		public ResourceMetadata(String baseName, ClassLoader loader)
		{
			this.baseName = baseName;
			this.loader = loader;
		}
	}
}
